package com.qf.business.goods.controller;

import com.qf.business.goods.service.GoodsSortNormsService;
import com.qf.business.goods.service.GoodsSortService;
import com.qf.data.base.r.R;
import com.qf.data.base.r.Rs;
import com.qf.data.base.utils.QfBeanUtils;
import com.qf.data.goods.entity.GoodsSort;
import com.qf.data.goods.vo.input.SortInput;
import com.qf.data.goods.vo.output.SortNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/sort")
@Slf4j
public class SortController {

    @Autowired
    private GoodsSortService goodsSortService;

    @Autowired
    private GoodsSortNormsService goodsSortNormsService;

    @RequestMapping("/setnorms")
    public R setNorms(Long sortId,String normsIdStr){
        log.info("[set sort norms] - 设置分类规格 - {} | {}",sortId,normsIdStr);
        goodsSortNormsService.updateSortNorms(sortId,normsIdStr.split("-"));
        return Rs.create(true);
    }

    @RequestMapping("/insert")
    public R insert(SortInput input){
        GoodsSort goodsSort = QfBeanUtils.beanCopy(input, GoodsSort.class);
        goodsSortService.save(goodsSort);
        return Rs.create(true);
    }

    /**
     * 查询树状三级列表
     * @return
     */
    @RequestMapping("/list")
    public R list(){
        //转换
        List<SortNode> nodes = new ArrayList<>();

        //准备一个map
        Map<Long,SortNode> nodeMap = new HashMap<>();
        List<GoodsSort> sorts = goodsSortService.list();
        for (GoodsSort sort : sorts) {
            SortNode sortNode = sort2Node(sort);
            nodeMap.put(sortNode.getId(),sortNode);
            if (sort.getPid() == null){
                //顶级分类
                nodes.add(sortNode);
            }else{
                //不是顶级分类
                //从map中获取上一级的Node节点
                SortNode parentNode = nodeMap.get(sort.getPid());
                parentNode.addNode(sortNode);
            }
        }

        return Rs.create(nodes);
    }

    /**
     * 将分类对象 转换成node节点对象
     * @param goodsSort
     * @return
     */
    private SortNode sort2Node(GoodsSort goodsSort){
        SortNode sortNode = new SortNode();
        sortNode.setId(goodsSort.getId());
        sortNode.setSortName(goodsSort.getSortName());
        return sortNode;
    }
    

}
